package net.daum.hibernate;

import java.util.List;

import net.daum.hibernate.domain.Message;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class HelloWorld {
	public static void run(SessionFactory sessionFactory) {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		
		Message message = new Message("Hello, World");				
		Long messageId = (Long) session.save(message);
		System.out.println("messageId:" + messageId);
		
		transaction.commit();
		//session.clear();
		
		session = sessionFactory.openSession();
		transaction = session.getTransaction();
		transaction.begin();
		
		List messageList= session.createQuery("from Message m order by m.text asc").list();
		System.out.println("size:" + messageList.size());
		
		for (int i = 0; i < messageList.size(); i++) {
			System.out.println(message);
		}
				
		transaction.commit();
		//session.close();
		
		// dirty check and cascading
		session = sessionFactory.openSession();
		transaction = session.getTransaction();
		transaction.begin();
		
		message = (Message) session.get(Message.class, messageId);
		message.setText("Test");
		message.setNextMessage(new Message("Hello"));		
		
		transaction.commit();
		session.close();
	}
	
	public static void main(String[] args) {
		run(HibernateUtil.getSessionFactory());				
	}
}